<?php
$page_title = 'قائمة المدارس';
require_once('includes/header.php');

// ============================================================
// معالجة الإجراءات (تنشيط/إيقاف/حذف)
// ============================================================
$msg = '';
$msg_type = 'success';

if (isset($_GET['action']) && isset($_GET['id'])) {
    $sid = (int)$_GET['id'];
    $action = $_GET['action'];
    
    if ($sid > 0) {
        // جلب بيانات المدرسة
        $sq = mysqli_query($conn, "SELECT * FROM schools WHERE school_id = $sid");
        $school = $sq ? mysqli_fetch_array($sq) : null;
        
        if ($school) {
            if ($action === 'toggle') {
                $new_status = $school['is_active'] ? 0 : 1;
                if (mysqli_query($conn, "UPDATE schools SET is_active = $new_status WHERE school_id = $sid")) {
                    $msg = $new_status 
                        ? 'تم تنشيط المدرسة: ' . $school['school_name']
                        : 'تم إيقاف المدرسة: ' . $school['school_name'];
                    log_activity($conn, 'تغيير حالة مدرسة', $school['school_name']);
                }
            } elseif ($action === 'delete') {
                // تحقق من وجود بيانات مرتبطة
                $chk = mysqli_query($conn, "SELECT COUNT(*) AS cnt FROM students WHERE school_id = $sid");
                $cnt = $chk ? (int)mysqli_fetch_array($chk)['cnt'] : 0;
                
                if ($cnt > 0) {
                    $msg = 'لا يمكن حذف المدرسة — تحتوي على ' . $cnt . ' طالب';
                    $msg_type = 'error';
                } else {
                    mysqli_query($conn, "DELETE FROM school_settings WHERE school_id = $sid");
                    mysqli_query($conn, "DELETE FROM fee_types WHERE school_id = $sid");
                    mysqli_query($conn, "DELETE FROM accounts WHERE school_id = $sid");
                    mysqli_query($conn, "DELETE FROM academic_years WHERE school_id = $sid");
                    mysqli_query($conn, "DELETE FROM users WHERE school_id = $sid");
                    mysqli_query($conn, "DELETE FROM schools WHERE school_id = $sid");
                    
                    $msg = 'تم حذف المدرسة: ' . $school['school_name'];
                    log_activity($conn, 'حذف مدرسة', $school['school_name']);
                }
            }
        }
    }
}

// ============================================================
// الفلاتر
// ============================================================
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';

$where_parts = array();
if (!empty($search)) {
    $s = mysqli_real_escape_string($conn, $search);
    $where_parts[] = "(school_name LIKE '%$s%' OR school_code LIKE '%$s%' OR phone LIKE '%$s%' OR email LIKE '%$s%')";
}
if ($status_filter !== '') {
    $where_parts[] = "is_active = " . (int)$status_filter;
}

$where_sql = count($where_parts) > 0 ? "WHERE " . implode(" AND ", $where_parts) : "";

// ============================================================
// جلب المدارس مع الإحصائيات
// ============================================================
$schools_q = mysqli_query($conn, "
    SELECT 
        s.*,
        (SELECT COUNT(*) FROM users u WHERE u.school_id = s.school_id AND u.is_active = 1) AS users_count,
        (SELECT COUNT(*) FROM students st WHERE st.school_id = s.school_id AND st.status = 'active') AS students_count,
        (SELECT COUNT(*) FROM classes c WHERE c.school_id = s.school_id) AS classes_count,
        (SELECT IFNULL(SUM(f.net_amount), 0) FROM fees f WHERE f.school_id = s.school_id) AS total_fees,
        (SELECT IFNULL(SUM(i.paid_amount), 0) FROM installments i WHERE i.school_id = s.school_id) AS total_paid
    FROM schools s
    $where_sql
    ORDER BY s.school_id DESC
");

$total_schools = $schools_q ? mysqli_num_rows($schools_q) : 0;
?>

<?php require_once('includes/sidebar.php'); ?>

<div class="span10 main-content">
    
    <div class="page-header">
        <div style="display:flex;justify-content:space-between;align-items:center">
            <h2>🏫 قائمة المدارس</h2>
            <a href="school_add.php" class="btn btn-success">
                ➕ إضافة مدرسة
            </a>
        </div>
    </div>
    
    <?php if (!empty($msg)): ?>
        <div class="alert alert-<?php echo $msg_type === 'error' ? 'error' : 'success'; ?>">
            <?php echo htmlspecialchars($msg); ?>
        </div>
    <?php endif; ?>
    
    <!-- ============ شريط الفلاتر ============ -->
    <div class="table-box">
        <form method="get" class="form-inline">
            <div class="row-fluid">
                <div class="span5">
                    <input type="text" name="search" class="input-block-level" 
                           placeholder="🔍 ابحث بالاسم أو الكود أو الهاتف..."
                           value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="span3">
                    <select name="status" class="input-block-level">
                        <option value="">— كل الحالات —</option>
                        <option value="1" <?php echo $status_filter === '1' ? 'selected' : ''; ?>>نشطة فقط</option>
                        <option value="0" <?php echo $status_filter === '0' ? 'selected' : ''; ?>>موقوفة فقط</option>
                    </select>
                </div>
                <div class="span4">
                    <button type="submit" class="btn btn-primary">
                        🔍 بحث
                    </button>
                    <a href="schools.php" class="btn">إعادة تعيين</a>
                </div>
            </div>
        </form>
    </div>
    
    <!-- ============ الإحصائيات ============ -->
    <div class="row-fluid" style="margin-top:15px">
        <div class="span3">
            <div class="stat-card">
                <div class="icon">🏫</div>
                <h3><?php echo $total_schools; ?></h3>
                <p>عدد النتائج</p>
            </div>
        </div>
        <?php
        // إجماليات
        $tot_users = 0;
        $tot_students = 0;
        $tot_paid = 0;
        if ($schools_q) {
            mysqli_data_seek($schools_q, 0);
            while ($r = mysqli_fetch_array($schools_q)) {
                $tot_users += (int)$r['users_count'];
                $tot_students += (int)$r['students_count'];
                $tot_paid += (float)$r['total_paid'];
            }
            mysqli_data_seek($schools_q, 0);
        }
        ?>
        <div class="span3">
            <div class="stat-card purple">
                <div class="icon">👥</div>
                <h3><?php echo $tot_users; ?></h3>
                <p>إجمالي المستخدمين</p>
            </div>
        </div>
        <div class="span3">
            <div class="stat-card green">
                <div class="icon">🎓</div>
                <h3><?php echo $tot_students; ?></h3>
                <p>إجمالي الطلاب</p>
            </div>
        </div>
        <div class="span3">
            <div class="stat-card orange">
                <div class="icon">💰</div>
                <h3><?php echo number_format($tot_paid, 0); ?></h3>
                <p>إجمالي المدفوع</p>
            </div>
        </div>
    </div>
    
    <!-- ============ الجدول ============ -->
    <div class="table-box" style="margin-top:20px">
        <table class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th width="50">#</th>
                    <th>المدرسة</th>
                    <th width="100">الكود</th>
                    <th width="120">التواصل</th>
                    <th width="70">المستخدمون</th>
                    <th width="70">الطلاب</th>
                    <th width="70">الصفوف</th>
                    <th width="120">إجمالي المدفوع</th>
                    <th width="80">الحالة</th>
                    <th width="200">إجراءات</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($total_schools > 0): ?>
                <?php while ($s = mysqli_fetch_array($schools_q)): ?>
                    <tr>
                        <td><?php echo (int)$s['school_id']; ?></td>
                        <td>
                            <strong><?php echo htmlspecialchars($s['school_name']); ?></strong>
                            <?php if (!empty($s['address'])): ?>
                                <br>
                                <small style="color:#7f8c8d">
                                    📍 <?php echo htmlspecialchars($s['address']); ?>
                                </small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="label label-info">
                                <?php echo htmlspecialchars($s['school_code']); ?>
                            </span>
                        </td>
                        <td>
                            <?php if (!empty($s['phone'])): ?>
                                <small>📞 <?php echo htmlspecialchars($s['phone']); ?></small><br>
                            <?php endif; ?>
                            <?php if (!empty($s['email'])): ?>
                                <small>✉️ <?php echo htmlspecialchars($s['email']); ?></small>
                            <?php endif; ?>
                        </td>
                        <td style="text-align:center">
                            <span class="badge"><?php echo (int)$s['users_count']; ?></span>
                        </td>
                        <td style="text-align:center">
                            <span class="badge badge-info"><?php echo (int)$s['students_count']; ?></span>
                        </td>
                        <td style="text-align:center">
                            <span class="badge badge-warning"><?php echo (int)$s['classes_count']; ?></span>
                        </td>
                        <td style="color:green;font-weight:bold">
                            <?php echo number_format($s['total_paid'], 2); ?>
                        </td>
                        <td>
                            <?php if ($s['is_active']): ?>
                                <span class="label label-success">✅ نشطة</span>
                            <?php else: ?>
                                <span class="label label-important">⏸️ موقوفة</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="school_view.php?id=<?php echo (int)$s['school_id']; ?>" 
                               class="btn btn-mini btn-info" title="عرض التفاصيل">
                                👁️
                            </a>
                            <a href="school_edit.php?id=<?php echo (int)$s['school_id']; ?>" 
                               class="btn btn-mini btn-warning" title="تعديل">
                                ✏️
                            </a>
                            <a href="?action=toggle&id=<?php echo (int)$s['school_id']; ?>" 
                               class="btn btn-mini btn-default" 
                               onclick="return confirm('<?php echo $s['is_active'] ? 'إيقاف' : 'تنشيط'; ?> المدرسة؟')"
                               title="<?php echo $s['is_active'] ? 'إيقاف' : 'تنشيط'; ?>">
                                <?php echo $s['is_active'] ? '⏸️' : '▶️'; ?>
                            </a>
                            <a href="?action=delete&id=<?php echo (int)$s['school_id']; ?>" 
                               class="btn btn-mini btn-danger"
                               onclick="return confirm('⚠️ تحذير!\n\nسيتم حذف المدرسة: <?php echo addslashes($s['school_name']); ?>\n\nهل أنت متأكد؟\n\nملاحظة: لا يمكن الحذف إذا كان هناك طلاب مسجلون.')"
                               title="حذف">
                                🗑️
                            </a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="10" style="text-align:center;padding:40px">
                        <div style="color:#999;font-size:18px">
                            <?php if (!empty($search) || $status_filter !== ''): ?>
                                🔍 لا توجد نتائج مطابقة للبحث
                                <br><br>
                                <a href="schools.php" class="btn">إلغاء الفلاتر</a>
                            <?php else: ?>
                                🏫 لا توجد مدارس مسجلة
                                <br><br>
                                <a href="school_add.php" class="btn btn-success">
                                    ➕ إضافة أول مدرسة
                                </a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
    
</div><!-- span10 -->

<?php require_once('includes/footer.php'); ?>